/* api */
import * as TaskApi from '@src/api/TaskApi';
import { filterProducts } from '@src/api/ProductV2Api';
/* components */
import ChooseServiceDialog from './components/ChooseServiceDialog.vue';
import ChoosePartDialog from './components/ChoosePartDialog.vue';
import ChooseMaterialDialog from './components/ChooseMaterialDialog.vue';
import PartSeviceTable from './components/PartSeviceTable.vue';
import MaterialTable from './components/MaterialTable.vue';
import FaultTable from './components/FaultTable.vue';
import TaskCard from '@src/modules/task/view/components/TaskCard/index.vue';
/* util */
import * as math from 'mathjs';
import i18n from '@src/locales'
import { getRootWindow } from '@src/util/dom';
/* model */
import { PART_SERVICE_LIST_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'part-sevice-list',
  props: {
    sparepartConfig: {
      type: Array,
      default: () => ([])
    },
    products: {
      type: Array,
      default: () => ([])
    },
    // 工单数据
    task: {
      type: Object,
      default: () => ({})
    },
    // 附加组件信息
    cardInfo: {
      type: Array,
      default: () => ([])
    },
    // 工单类型的配置
    taskOptions: {
      type: Object,
      default: () => ({})
    },
    // 自定义的附加组件
    customCardList: {
      type: Array,
      default: () => ([])
    },
    propsForSubComponents: {
      type: Object,
      default: () => ({})
    },
    cardForms: {
      type: Array,
      default: () => ([])
    },
    showSparepartServiceList: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeTab: '',
      // 备件清单列表数据
      sparepartData: [],
      // 服务项目列表数据
      serviceData: [],
      // 物料申领列表数据
      materialData: [],
      // 故障清单列表数据
      faultData: [],
      // 当前租户备件配置
      partConfig: {},
      warrantyStatusData: [
        {
          value: 0,
          label: i18n.t('common.base.warranty')
        },
        {
          value: 1,
          label: i18n.t('common.base.surrender')
        }
      ],
      productTemplate: [],
      internationalGray,
    }
  },
  computed: {
    /** 备件清单 */
    sparepart() {
      return this.sparepartConfig.find(item => item.specialfrom == '备件清单') || {};
    },
    /** 是否显示备件清单 */
    showSpartpart() {
      return Object.keys(this.sparepart).length > 0;
    },
    /** 备件清单字段 */
    sparepartColums() {
      let { fields = [] } = this.sparepart;
      fields = fields.filter(field => field.enabled && !field.isHidden);

      // 设置备件名称、预计用量列宽
      fields.forEach(field => {
        if (field.fieldName == 'name') {
          field.width = '160px';
        } else if (field.fieldName == 'preNum') {
          field.width = '100px';
        }
      })

      fields.push({
        fieldName: 'action',
        displayName: i18n.t('common.base.operation')
      })

      // 新建工单-备件清单 是否展示终端销售价和小计
      if(!this.serviceProviderShowPrice) {
        fields = fields.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'total')
      }

      return fields;
    },
    /** 服务项目 */
    serviceItem() {
      return this.sparepartConfig.find(item => item.specialfrom == '服务清单') || {};
    },
    /** 是否显示服务项目 */
    showService() {
      return Object.keys(this.serviceItem).length > 0;
    },
    /** 服务项目字段 */
    serviceColums() {
      let { fields = [] } = this.serviceItem;
      fields = fields.filter(field => field.enabled && !field.isHidden);

      // 设置服务项目名称、预计用量列宽
      fields.forEach(field => {
        if (field.fieldName == 'name' || field.fieldName == 'preNum') {
          field.width = '108px';
        }
        if(this.editUnitPrice && field.fieldName == 'salePrice') {
          field.width = this.internationalGray ? '220px' : '100px';
        }
      })

      fields.push({
        fieldName: 'action',
        displayName: i18n.t('common.base.operation')
      })

      // 新建工单-服务项目 是否展示终端销售价和小计
      if(!this.serviceProviderShowPrice) {
        fields = fields.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'total')
      }

      return fields;
    },
    /** 物料申领 */
    materialItem() {
      return this.sparepartConfig.find(item => item.specialfrom == '物料申领') || {}
    },
    /** 是否显示物料申领 */
    showMaterial() {
      return Object.keys(this.materialItem).length > 0
    },
    /** 物料申领字段 */
    materialColums() {
      let { fields = [] } = this.materialItem;
      fields = fields.filter(field => field.enabled && !field.isHidden && field.fieldName !== 'warrantyStatus' && field.fieldName !== 'warrantyConfirmation' && field.fieldName !== 'applyNum' && field.fieldName !== 'paasApproveNum' && field.fieldName !== 'usedNum')

      // 新建工单-物料申领、添加物料、选择物料 是否展示终端销售价和小计
      if(!this.serviceProviderShowPrice) {
        fields = fields.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'total')
      }

      // 设置物料申领名称、预计用量列宽
      fields.forEach(field => {
        if (field.fieldName == 'name' || field.fieldName == 'snManage') {
          field.width = '140px';
        } else if (field.fieldName == 'preNum') {
          field.width = '140px';
        }

        // 小计 & 预计用量固定
        if (field.fieldName == 'total' || field.fieldName == 'preNum') {
          field.isFixed = 'right';
        }
        field.tooltip = field.fieldName == 'preNum' ? false : true;
      })
      fields.push({
        fieldName: 'action',
        displayName: i18n.t('common.base.operation'),
        isFixed: 'right'
      })

      return fields;
    },
    /** 故障清单 */
    faultList() {
      return this.sparepartConfig.find(item => item.specialfrom == '故障清单') || {}
    },
    // 新建权限
    addFaultAuth() {
      return this.faultList?.canAdd || false
    },
    /** 是否显示故障清单 */
    showFaultList() {
      return Object.keys(this.faultList).length > 0;
    },
    /** 
    * @description 物料申领附加组件配置
    */
    materialConfig() {
      return JSON.parse(this.materialItem.config || '{}')
    },
    /** 
    * @description 允许在添加物料时修改物料质保状态
    */
    allowWarrantyChange() {
      let { warrantyChange, warrantyRoleList = [] } = this.materialConfig
      let hasAuthRole = (this.isExecutor && warrantyRoleList.includes('taskPrincipalPerson')) || (this.isSynergies && warrantyRoleList.includes('taskSynergyPerson'));
      return warrantyChange && hasAuthRole
    },
    editUnitPrice() {
      return this.taskOptions?.editUnitPrice || false;
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    }
  },
  async mounted() {
    this.reset();

    try {
      // 工单草稿状态时获取附加组件的数据
      if (this.task.isDelete == 5) {
        const getInventoryList = ['备件清单', '服务清单', '物料申领', '故障清单'];
        const partSeviceList = this.cardInfo.filter(x => getInventoryList.includes(x.specialfrom));

        // '备件清单', '服务清单', '物料申领', '故障清单'等
        partSeviceList.forEach(c => {
          TaskApi.getInventoryByCardId({
            cardId: c.cardId,
            taskId: this.task.id
          }).then(res => {
            if (res.success && res.result) {
              const arr = res.result || []
              arr.map(item => {
                if (c.specialfrom == '物料申领') {
                  item.relatedId = Number(item.relatedId)
                }
                item.id = item.relatedId
                return item
              })
              if (c.specialfrom == '备件清单') this.sparepartData = arr
              if (c.specialfrom == '服务清单') this.serviceData = arr
              if (c.specialfrom == '物料申领') this.materialData = arr
              if (c.specialfrom == '故障清单') this.faultData = arr
            }
          })
        })
      }
    } catch(err) {
      console.error('get part config error:', err);
    }
  },
  watch: {
    showSpartpart(newVal) {
      // 获取当前租户的备件配置
      if (newVal && Object.keys(this.partConfig).length == 0) {
        TaskApi.sparepartConfig().then(res => {
          if (res.success) this.partConfig = res.result || {}
        })
      }
    },
    customCardList: {
      handler(val) {
        this.setActiveTab();
      }
    }
  },
  methods: {
    /** 打开添加备件弹窗 */
    openChoosePartDialog() {
      if (!this.sparepart.canAdd) return this.$platform.alert(i18n.t('task.tip.editTip5'));

      this.$refs.choosePartDialog.open();
    },
    /** 添加已选备件 */
    addChoosePart(data) {
      // 过滤掉空数据
      data = data.filter(item => item.id);
      
      // 是否超过最大限制
      let isOverLimit = this.sparepartData.length + data.length > PART_SERVICE_LIST_MAX_LENGTH;
      if (isOverLimit) return this.$platform.alert(PART_SERVICE_LIST_MAX_LENGTH_MESSAGE);

      if (data.length == 0) return this.$platform.alert(i18n.t('task.tip.addPartTip1'));

      // 查找已添加的备件中是否存在该备件
      data.forEach(item => {
        let ids = this.sparepartData.findIndex(val => val.id == item.id);

        if (ids > -1) {
          this.sparepartData[ids].preNum = Number(math.add(math.bignumber(this.sparepartData[ids].preNum), math.bignumber(item.preNum)));
        } else {
          this.sparepartData.push(item);
        }
      })

      this.$refs.choosePartDialog.close();
    },
    /** 打开添加服务项目弹窗 */
    openChooseServiceDialog() {
      if (!this.serviceItem.canAdd) return this.$platform.alert(i18n.t('task.tip.editTip5'));

      this.$refs.chooseServiceDialog.open();
    },
    /** 添加已选服务项目 */
    addChooseService(data) {
      // 是否超过最大限制
      let isOverLimit = this.serviceData.length + data.length > PART_SERVICE_LIST_MAX_LENGTH;
      if (isOverLimit) return this.$platform.alert(PART_SERVICE_LIST_MAX_LENGTH_MESSAGE);

      if (data.length == 0) return this.$platform.alert(i18n.t('task.tip.serviceTip'));

      // 查找已添加的服务项目中是否存在该服务项目
      data.forEach(item => {
        let ids = this.serviceData.findIndex(val => val.id == item.id);

        if (ids > -1) {
          this.serviceData[ids].preNum = Number(math.add(math.bignumber(this.serviceData[ids].preNum), 1));
        } else {
          this.serviceData.push({...item, preNum: 1});
        }
      })

      this.$refs.chooseServiceDialog.close();
    },
    async fetchProduct() {
      try {
        let params = (this.products || []).map(item => {
          return item.id;
        });
        const res = await filterProducts(params);
        if (!res.success) return;
        this.productTemplate = res.result || [];
      } catch (error) {
        console.error('搜索产品 function catch err', error);
      } finally {
      }
    },
    /** 打开添加物料弹窗 */
    openChooseMaterialDialog() {
      if (!this.materialItem.canAdd) return this.$platform.alert(i18n.t('task.tip.editTip5'));

      this.$refs.chooseMaterialDialog.open();
      this.fetchProduct();
    },
    /** 添加已选物料申领 */
    addChooseMaterial(data) {
      // 过滤掉空数据
      let selectedData = data.filter(item => item.id);
      if (selectedData.length == 0) return this.$platform.alert(i18n.t('task.tip.applyMaterialTip1'));

      // 是否超过最大限制
      let isOverLimit = this.materialData.length + selectedData.length > PART_SERVICE_LIST_MAX_LENGTH;
      if (isOverLimit) return this.$platform.alert(PART_SERVICE_LIST_MAX_LENGTH_MESSAGE);

      selectedData.forEach(item => {
        let ids = this.materialData.findIndex(val => val.id === item.id);
        if(ids > -1) {
          this.materialData[ids].preNum = Number(math.add(math.bignumber(this.materialData[ids].preNum), math.bignumber(item.preNum)));
        } else {
          this.materialData.push(item);
        }
      })
      
      this.$refs.chooseMaterialDialog.close()
    },
    /** 添加故障清单 */
    async addChooseFault(data) {
      this.faultData = data;
    },
    /** 重置 */
    reset() {
      this.sparepartData = [];
      this.serviceData = [];
      this.setActiveTab()
    },
    setActiveTab() {
      if (this.showSpartpart) {
        this.activeTab = 'sparepart'
        return
      }
      if (this.showService) {
        this.activeTab = 'service'
        return
      }
      if (this.showMaterial) {
        this.activeTab = 'material'
        return
      }
      if (this.showFaultList) {
        this.activeTab = 'faultList';
        return
      }
      // 其他没有则默认设置自定义附加组件
      if(!(this.showSpartpart || this.showService || this.showMaterial || this.showFaultList) && this.customCardList.length) {
        this.activeTab = this.customCardList?.[0]?.cardId;
        return;
      }
    }
  },
  components: {
    [ChooseServiceDialog.name]: ChooseServiceDialog,
    [ChoosePartDialog.name]: ChoosePartDialog,
    [ChooseMaterialDialog.name]: ChooseMaterialDialog,
    [PartSeviceTable.name]: PartSeviceTable,
    [MaterialTable.name]: MaterialTable,
    [FaultTable.name]: FaultTable,
    [TaskCard.name]: TaskCard,
  }
}